<template>
  <div class="uploadWrapper">
    <vuedraggable
      class="vue-draggable"
      :class="{ single: isSingle, maxHidden: isMaxHidden }"
      tag="ul"
      v-model="imgList"
      draggable=".draggable-item"
      @start="onDragStart"
      @end="onDragEnd"
    >
      <!-- 拖拽元素 -->
      <li
        v-for="(item, index) in imgList"
        :key="item + index"
        class="draggable-item"
        
      >
        <div class="advert-img-wrapper">
          <el-image :style="{width:'80px',height:'80px'}" class="advert-img" :src="item.img" :preview-src-list="[item.img]"></el-image>
          <div class="link-info">
            <div class="link-type">链接类型:{{item.link_type_name}}</div>
            <div class="link-url">链接地址：{{item.link_url}}</div>
          </div>
        </div>
        <div class="shadow">
          <i class="el-icon-edit" style="font-size:30px;"  @click="onEditHandler(index)"></i>
          <i class="el-icon-delete" style="font-size:30px;"  @click="onRemoveHandler(index)"></i>
        </div>
        
      </li>
      <!-- 上传按钮 -->
      
    </vuedraggable>
    <el-button @click="onAddHandler">添加</el-button>
    <el-dialog :title="dialogTitle" width="600px" :visible.sync="showAdvertDialog" :append-to-body="true" :close-on-click-modal="false">
      <div class="form">
        <div class="form-left">
          <el-upload
            name="uploadFileData"
            ref="uploadRef"
            class="uploadBox"
            :style="{ width:'200px', height:'200px' }"
            :data="uploadPlatformData"
            :action="uploadUrl"
            :headers="uploadHeaders"
            accept=".jpg,.jpeg,.png,.gif"
            :show-file-list="false"
            :multiple="false"
            :limit="limit"
            :before-upload="beforeUpload"
            :on-success="onSuccessUpload"
            :on-exceed="onExceed"
          >
            <el-image v-if="!isUploading && this.uploadImg" :style="{width:'200px',height:'200px'}" fit="contain"   :src="this.uploadImg"></el-image>
            <i class="el-icon-plus uploadIcon" v-if="isUploading || !this.uploadImg">
              <span class="uploading" v-show="isUploading">正在上传...</span>
              <span
                v-if="!isUploading && limit && limit!==99 && !isSingle"
                class="limitTxt"
              >最多{{ limit }}张</span>
            </i>
          </el-upload>
        </div>
        <div class="form-right">
          <div class="form-item">
            <div class="form-label">链接类型：</div>
            <div clas="form-value">
              <el-select style="width:300px;" v-model="linkType">
                <el-option v-for="item in advertTypeList" :key="item.value" :value="''+item.value" :label="item.label"></el-option>
              </el-select>
            </div>
          </div>
          <div class="form-item">
            <div class="form-label">链接地址：</div>
            <div clas="form-value">
              <el-input style="width:300px;"  placeholder="链接地址" v-model="linkUrl"></el-input>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showAdvertDialog = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import vuedraggable from 'vuedraggable'
import {validImgUpload,createUniqueString} from './uploadTool'
import {getSySHyperlinkTypeList} from '@/api/sys';

export default {
  name: 'hyperlinkUploader',

  props: {
    // 图片数据(图片url组成的数组) 通过v-model传递
    value: {
      type: Array,
      default () {
        return []
      }
    },
    // 限制上传的图片数量
    limit: {
      type: Number,
      default: 99
    },
    // 限制上传图片的文件大小(kb)
    size: {
      type: Number,
      default: 500
    },
    // 是否是单图上传(单图上传就是已传图片和上传按钮重叠)
    isSingle: {
      type: Boolean,
      default: false
    },
    // 是否使用图片压缩
    useCompress: {
      type: Boolean,
      default: false
    },
    // 图片显示的宽度(px)
    width: {
      type: Number,
      default: 100
    },
    // 图片显示的高度(px)
    height: {
      type: Number,
      default: 100
    }
  },

  data () {
    return {
      showAdvertDialog:false,
      dialogTitle:'添加图片',
      uploadImg:'',
      linkType:'',
      linkUrl:'',
      editAdvertIndex:'',
      advertTypeList:[],
      advertTypeObj:{},
      uploadUrl:this.$config.requestUrl+'/' + this.$config.app+'/' + this.$config.version + '/Upload/uploadImage',
      uploadHeaders:this.$store.getters.userInfo.user_token ? {'User-Token' :this.$store.getters.userInfo.user_token} : {},
      uploadPlatformData:{
        platform_app_id:this.$store.getters.appInfo.platform_app_id,
        platform_user_id:this.$store.getters.appInfo.platform_user_id,
        platform_app_user_id:this.$store.getters.appInfo.platform_app_user_id
      },
      isUploading: false, // 正在上传状态
      isFirstMount: true // 控制防止重复回显
    }
  },

  computed: {
    // 图片数组数据
    imgList: {
      get () {
        return this.value
      },
      set (val) {
        // 同步v-model
        this.$emit('update:value', val);
      }
    },
    // 控制达到最大限制时隐藏上传按钮
    isMaxHidden () {
      return this.imgList.length >= this.limit
    },
  },

  mounted () {

  },
  created(){
    getSySHyperlinkTypeList().then(data=>{
      this.advertTypeList = data;
      data.forEach(item=>{
        this.advertTypeObj[item.value] = item.label;
      })
    })
  },
  methods: {

    submit(){
      if (this.imgList.length < this.limit) {
        if (this.uploadImg) {
          if (this.editAdvertIndex === '') {
            this.imgList.push({img:this.uploadImg,link_url:this.linkUrl,link_type:this.linkType,link_type_name:this.advertTypeObj[this.linkType]});
          } else {
            this.imgList[this.editAdvertIndex] = {img:this.uploadImg,link_url:this.linkUrl,link_type:this.linkType,link_type_name:this.advertTypeObj[this.linkType]};
          }
          
          this.showAdvertDialog = false;
        } else {
          this.$tool.errorToast('请先上传图片');
        }
      }
    },
    // 上传图片之前
    beforeUpload (file) {
      this.isFirstMount = false
      if (this.useCompress) {
        // 图片压缩
        return new Promise((resolve, reject) => {
          lrz(file, { width: 1920 }).then((rst) => {
            file = rst.file
          }).always(() => {
            if (validImgUpload(file, this.size)) {
              this.isUploading = true
              resolve()
            } else {
              reject(new Error())
            }
          })
        })
      } else {
        if (validImgUpload(file, this.size)) {
          this.isUploading = true
          return true
        } else {
          return false
        }
      }
    },
    // 上传完单张图片
    onSuccessUpload (res, file, fileList) {
      if (res.type == 'ok') {
        this.uploadImg = res.data.url;
      } else {
        this.$message({ type: 'error', message: res.msg })
      }
      this.isUploading = false
    },
    //新增图片
    onAddHandler(){
      this.uploadImg = '';
      this.linkUrl = '';
      this.linkType = '';
      this.editAdvertIndex = '';
      this.dialogTitle = '添加图片';
      this.showAdvertDialog = true;
    },
    // 修改单张图片
    onEditHandler (index) {
      this.uploadImg = this.imgList[index].img;
      this.linkUrl = this.imgList[index].link_url;
      this.linkType = this.imgList[index].link_type;
      this.editAdvertIndex = index;
      this.dialogTitle = '修改图片';
      this.showAdvertDialog = true;
    },
    // 移除单张图片
    onRemoveHandler (index) {
      this.$confirm('确定删除该图片?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.value.splice(index,1);
        })
        .catch(() => {})
    },
    // 超限
    onExceed () {
      this.$refs.uploadRef.abort() // 取消剩余接口请求
      this.$message({
        type: 'warning',
        message: `图片超限，最多可上传${this.limit}张图片`
      })
    },
    onDragStart (e) {
      e.target.classList.add('hideShadow')
    },
    onDragEnd (e) {
      e.target.classList.remove('hideShadow')
    }
  },

  components: { vuedraggable }
}
</script>

<style lang="less" scoped>
/deep/ .el-upload {
  width: 100%;
  height: 100%;
}

// 上传按钮
.uploadIcon {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #c0ccda;
  background-color: #fbfdff;
  border-radius: 6px;
  font-size: 20px;
  color: #999;

  .limitTxt,
  .uploading {
    position: absolute;
    bottom: 10%;
    left: 0;
    width: 100%;
    font-size: 14px;
    text-align: center;
  }
}

// 拖拽
.vue-draggable {
  display: flex;
  flex-wrap: wrap;
  padding-left:0;
  .draggable-item {
    margin-right: 5px;
    margin-bottom: 5px;
    background:#F4F4F4;
    width:100%;
    padding:15px;
    margin-bottom:10px;
    border-radius: 6px;
    position: relative;
    overflow: hidden;

    .el-image {
      width: 100%;
      height: 100%;
    }
    .shadow {
      position: absolute;
      top: 0;
      right: 0;
      background-color: rgba(0,0,0,.5);
      opacity: 0;
      transition: opacity .3s;
      color: #fff;
      font-size: 20px;
      line-height: 20px;
      padding: 2px;
      cursor: pointer;
    }
    &:hover {
      .shadow {
        opacity: 1;
      }
    }
  }
  &.hideShadow {
    .shadow {
      display: none;
    }
  }
  &.single {
    overflow: hidden;
    position: relative;

    .draggable-item {
      position: absolute;
      left: 0;
      top: 0;
      z-index: 1;
    }
  }
  &.maxHidden {
    .uploadBox {
      display: none;
    }
  }
}
// el-image
.el-image-viewer__wrapper {
  .el-image-viewer__mask {
    opacity: .8;
  }
  .el-icon-circle-close {
    color: #fff;
  }
}
.advert-img-wrapper{display: flex;align-items: center;}
.form{display: flex; align-items:center;}
.form-left{flex:0 0 200px;}
.form-right{padding-left:20px;}
.form-label{padding:12px 0;}
.link-info{font-size:13px;padding-left:10px;}
.link-url{color:#808080;}
</style>
